using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Win32;
using System.Globalization;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 写书流程配置对话框
    /// </summary>
    public partial class WritingWorkflowConfigDialog : Window
    {
        private readonly ILogger<WritingWorkflowConfigDialog> _logger;
        private readonly IWritingWorkflowConfigService _workflowConfigService;
        private List<WritingWorkflowConfig> _configs = new();
        private WritingWorkflowConfig? _currentConfig;

        public WritingWorkflowConfigDialog()
        {
            InitializeComponent();
            
            _logger = App.ServiceProvider?.GetService<ILogger<WritingWorkflowConfigDialog>>() 
                ?? throw new InvalidOperationException("无法获取日志服务");
            
            _workflowConfigService = App.ServiceProvider?.GetService<IWritingWorkflowConfigService>() 
                ?? throw new InvalidOperationException("无法获取写书流程配置服务");

            Loaded += WritingWorkflowConfigDialog_Loaded;
        }

        private async void WritingWorkflowConfigDialog_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                await LoadConfigsAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载写书流程配置时发生错误");
                MessageBox.Show($"加载写书流程配置时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 加载所有配置
        /// </summary>
        private async Task LoadConfigsAsync()
        {
            try
            {
                _configs = await _workflowConfigService.GetAllConfigsAsync();
                
                // 如果没有配置，创建默认配置
                if (!_configs.Any())
                {
                    var newDefaultConfig = await _workflowConfigService.CreateDefaultConfigAsync();
                    _configs.Add(newDefaultConfig);
                }

                ConfigListBox.ItemsSource = _configs;

                // 选择默认配置或第一个配置
                var defaultConfig = _configs.FirstOrDefault(c => c.IsDefault) ?? _configs.FirstOrDefault();
                if (defaultConfig != null)
                {
                    ConfigListBox.SelectedItem = defaultConfig;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载配置列表失败");
                throw;
            }
        }

        /// <summary>
        /// 配置选择变更事件
        /// </summary>
        private void ConfigListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ConfigListBox.SelectedItem is WritingWorkflowConfig config)
            {
                LoadConfigToUI(config);
            }
        }

        /// <summary>
        /// 将配置加载到界面
        /// </summary>
        private void LoadConfigToUI(WritingWorkflowConfig config)
        {
            _currentConfig = config;
            
            // 基本信息
            ConfigNameTextBox.Text = config.Name;
            ConfigDescriptionTextBox.Text = config.Description;
            IsDefaultCheckBox.IsChecked = config.IsDefault;
            
            // 基础流程设定
            EnableOverallOutlineCheckBox.IsChecked = config.EnableOverallOutlineGeneration;
            EnableWorldSettingCheckBox.IsChecked = config.EnableWorldSettingGeneration;
            EnableVolumeOutlineCheckBox.IsChecked = config.EnableVolumeOutlineGeneration;
            EnableChapterOutlineCheckBox.IsChecked = config.EnableChapterOutlineGeneration;
            EnableChapterContentCheckBox.IsChecked = config.EnableChapterContentGeneration;
            EnableTimelineUpdateCheckBox.IsChecked = config.EnableTimelineUpdate;
            
            SequentialModeRadio.IsChecked = config.EnableSequentialMode;
            BatchModeRadio.IsChecked = config.EnableBatchMode;
            
            // 生成参数
            OverallOutlineMaxTokensTextBox.Text = config.OverallOutlineMaxTokens.ToString();
            WorldSettingMaxTokensTextBox.Text = config.WorldSettingMaxTokens.ToString();
            VolumeOutlineMaxTokensTextBox.Text = config.VolumeOutlineMaxTokens.ToString();
            ChapterOutlineMaxTokensTextBox.Text = config.ChapterOutlineMaxTokens.ToString();
            ChapterContentMaxTokensTextBox.Text = config.ChapterContentMaxTokens.ToString();
            TimelineUpdateMaxTokensTextBox.Text = config.TimelineUpdateMaxTokens.ToString();
            
            OverallOutlineTemperatureTextBox.Text = config.OverallOutlineTemperature.ToString("F1", CultureInfo.InvariantCulture);
            WorldSettingTemperatureTextBox.Text = config.WorldSettingTemperature.ToString("F1", CultureInfo.InvariantCulture);
            VolumeOutlineTemperatureTextBox.Text = config.VolumeOutlineTemperature.ToString("F1", CultureInfo.InvariantCulture);
            ChapterOutlineTemperatureTextBox.Text = config.ChapterOutlineTemperature.ToString("F1", CultureInfo.InvariantCulture);
            ChapterContentTemperatureTextBox.Text = config.ChapterContentTemperature.ToString("F1", CultureInfo.InvariantCulture);
            TimelineUpdateTemperatureTextBox.Text = config.TimelineUpdateTemperature.ToString("F1", CultureInfo.InvariantCulture);
            
            // 流程控制
            RetryCountTextBox.Text = config.RetryCount.ToString();
            GenerationIntervalTextBox.Text = config.GenerationInterval.ToString();
            EnableAutoSaveCheckBox.IsChecked = config.EnableAutoSave;
            AutoSaveIntervalTextBox.Text = config.AutoSaveInterval.ToString();
            
            PreviousChaptersForOutlineTextBox.Text = config.PreviousChaptersForOutline.ToString();
            PreviousChaptersForContentTextBox.Text = config.PreviousChaptersForContent.ToString();
            MaxWorldSettingFilesTextBox.Text = config.MaxWorldSettingFiles.ToString();
            MaxWorldSettingFileLengthTextBox.Text = config.MaxWorldSettingFileLength.ToString();
            
            // 文件输出
            OutputFileFormatComboBox.Text = config.OutputFileFormat;
            EnableAutoFileNameCheckBox.IsChecked = config.EnableAutoFileName;
            FileNameTemplateTextBox.Text = config.FileNameTemplate;
            EnableAutoChapterTitleCheckBox.IsChecked = config.EnableAutoChapterTitle;
            IncludeChapterNumberInFileNameCheckBox.IsChecked = config.IncludeChapterNumberInFileName;
            
            // 质量控制
            EnableConsistencyCheckCheckBox.IsChecked = config.EnableConsistencyCheck;
            EnableDuplicationCheckCheckBox.IsChecked = config.EnableDuplicationCheck;
            DuplicationThresholdTextBox.Text = config.DuplicationThreshold.ToString("F1", CultureInfo.InvariantCulture);
            EnableWordCountControlCheckBox.IsChecked = config.EnableWordCountControl;
            WordCountToleranceTextBox.Text = config.WordCountTolerance.ToString("F1", CultureInfo.InvariantCulture);
            EnableCrossVolumeTimelineReferenceCheckBox.IsChecked = config.EnableCrossVolumeTimelineReference;
            MaxCrossVolumeTimelineLengthTextBox.Text = config.MaxCrossVolumeTimelineLength.ToString();
        }

        /// <summary>
        /// 从界面获取配置
        /// </summary>
        private WritingWorkflowConfig GetConfigFromUI()
        {
            var config = _currentConfig ?? new WritingWorkflowConfig();
            
            // 基本信息
            config.Name = ConfigNameTextBox.Text.Trim();
            config.Description = ConfigDescriptionTextBox.Text.Trim();
            config.IsDefault = IsDefaultCheckBox.IsChecked == true;
            config.UpdatedAt = DateTime.Now;
            
            // 基础流程设定
            config.EnableOverallOutlineGeneration = EnableOverallOutlineCheckBox.IsChecked == true;
            config.EnableWorldSettingGeneration = EnableWorldSettingCheckBox.IsChecked == true;
            config.EnableVolumeOutlineGeneration = EnableVolumeOutlineCheckBox.IsChecked == true;
            config.EnableChapterOutlineGeneration = EnableChapterOutlineCheckBox.IsChecked == true;
            config.EnableChapterContentGeneration = EnableChapterContentCheckBox.IsChecked == true;
            config.EnableTimelineUpdate = EnableTimelineUpdateCheckBox.IsChecked == true;
            
            config.EnableSequentialMode = SequentialModeRadio.IsChecked == true;
            config.EnableBatchMode = BatchModeRadio.IsChecked == true;
            
            // 生成参数
            if (int.TryParse(OverallOutlineMaxTokensTextBox.Text, out int overallTokens))
                config.OverallOutlineMaxTokens = overallTokens;
            if (int.TryParse(WorldSettingMaxTokensTextBox.Text, out int worldTokens))
                config.WorldSettingMaxTokens = worldTokens;
            if (int.TryParse(VolumeOutlineMaxTokensTextBox.Text, out int volumeTokens))
                config.VolumeOutlineMaxTokens = volumeTokens;
            if (int.TryParse(ChapterOutlineMaxTokensTextBox.Text, out int chapterOutlineTokens))
                config.ChapterOutlineMaxTokens = chapterOutlineTokens;
            if (int.TryParse(ChapterContentMaxTokensTextBox.Text, out int chapterContentTokens))
                config.ChapterContentMaxTokens = chapterContentTokens;
            if (int.TryParse(TimelineUpdateMaxTokensTextBox.Text, out int timelineTokens))
                config.TimelineUpdateMaxTokens = timelineTokens;
            
            if (float.TryParse(OverallOutlineTemperatureTextBox.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out float overallTemp))
                config.OverallOutlineTemperature = overallTemp;
            if (float.TryParse(WorldSettingTemperatureTextBox.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out float worldTemp))
                config.WorldSettingTemperature = worldTemp;
            if (float.TryParse(VolumeOutlineTemperatureTextBox.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out float volumeTemp))
                config.VolumeOutlineTemperature = volumeTemp;
            if (float.TryParse(ChapterOutlineTemperatureTextBox.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out float chapterOutlineTemp))
                config.ChapterOutlineTemperature = chapterOutlineTemp;
            if (float.TryParse(ChapterContentTemperatureTextBox.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out float chapterContentTemp))
                config.ChapterContentTemperature = chapterContentTemp;
            if (float.TryParse(TimelineUpdateTemperatureTextBox.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out float timelineTemp))
                config.TimelineUpdateTemperature = timelineTemp;
            
            // 流程控制
            if (int.TryParse(RetryCountTextBox.Text, out int retryCount))
                config.RetryCount = retryCount;
            if (int.TryParse(GenerationIntervalTextBox.Text, out int interval))
                config.GenerationInterval = interval;
            config.EnableAutoSave = EnableAutoSaveCheckBox.IsChecked == true;
            if (int.TryParse(AutoSaveIntervalTextBox.Text, out int autoSaveInterval))
                config.AutoSaveInterval = autoSaveInterval;
            
            if (int.TryParse(PreviousChaptersForOutlineTextBox.Text, out int prevOutline))
                config.PreviousChaptersForOutline = prevOutline;
            if (int.TryParse(PreviousChaptersForContentTextBox.Text, out int prevContent))
                config.PreviousChaptersForContent = prevContent;
            if (int.TryParse(MaxWorldSettingFilesTextBox.Text, out int maxFiles))
                config.MaxWorldSettingFiles = maxFiles;
            if (int.TryParse(MaxWorldSettingFileLengthTextBox.Text, out int maxLength))
                config.MaxWorldSettingFileLength = maxLength;
            
            // 文件输出
            config.OutputFileFormat = OutputFileFormatComboBox.Text;
            config.EnableAutoFileName = EnableAutoFileNameCheckBox.IsChecked == true;
            config.FileNameTemplate = FileNameTemplateTextBox.Text.Trim();
            config.EnableAutoChapterTitle = EnableAutoChapterTitleCheckBox.IsChecked == true;
            config.IncludeChapterNumberInFileName = IncludeChapterNumberInFileNameCheckBox.IsChecked == true;
            
            // 质量控制
            config.EnableConsistencyCheck = EnableConsistencyCheckCheckBox.IsChecked == true;
            config.EnableDuplicationCheck = EnableDuplicationCheckCheckBox.IsChecked == true;
            if (float.TryParse(DuplicationThresholdTextBox.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out float dupThreshold))
                config.DuplicationThreshold = dupThreshold;
            config.EnableWordCountControl = EnableWordCountControlCheckBox.IsChecked == true;
            if (float.TryParse(WordCountToleranceTextBox.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out float wordTolerance))
                config.WordCountTolerance = wordTolerance;
            config.EnableCrossVolumeTimelineReference = EnableCrossVolumeTimelineReferenceCheckBox.IsChecked == true;
            if (int.TryParse(MaxCrossVolumeTimelineLengthTextBox.Text, out int maxTimelineLength))
                config.MaxCrossVolumeTimelineLength = maxTimelineLength;
            
            return config;
        }

        /// <summary>
        /// 新建配置
        /// </summary>
        private void NewConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var newConfig = new WritingWorkflowConfig
                {
                    Name = "新配置",
                    Description = "请输入配置描述",
                    CreatedAt = DateTime.Now,
                    UpdatedAt = DateTime.Now
                };

                LoadConfigToUI(newConfig);
                ConfigNameTextBox.Focus();
                ConfigNameTextBox.SelectAll();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建新配置时发生错误");
                MessageBox.Show($"创建新配置时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var config = GetConfigFromUI();

                // 验证配置
                if (string.IsNullOrWhiteSpace(config.Name))
                {
                    MessageBox.Show("请输入配置名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 保存配置
                if (config.Id == 0)
                {
                    await _workflowConfigService.SaveConfigAsync(config);
                }
                else
                {
                    await _workflowConfigService.UpdateConfigAsync(config);
                }

                // 如果设为默认，更新默认配置
                if (config.IsDefault)
                {
                    await _workflowConfigService.SetDefaultConfigAsync(config.Id);
                }

                // 重新加载配置列表
                await LoadConfigsAsync();

                MessageBox.Show("配置保存成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存配置时发生错误");
                MessageBox.Show($"保存配置时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 应用配置
        /// </summary>
        private async void ApplyConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentConfig?.Id > 0)
                {
                    await _workflowConfigService.ApplyConfigToServiceAsync(_currentConfig.Id);
                    MessageBox.Show("配置应用成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show("请先选择一个配置", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "应用配置时发生错误");
                MessageBox.Show($"应用配置时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 设为默认配置
        /// </summary>
        private async void SetDefault_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentConfig?.Id > 0)
                {
                    await _workflowConfigService.SetDefaultConfigAsync(_currentConfig.Id);
                    await LoadConfigsAsync();
                    MessageBox.Show("已设为默认配置", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置默认配置时发生错误");
                MessageBox.Show($"设置默认配置时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 删除配置
        /// </summary>
        private async void DeleteConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentConfig?.Id > 0)
                {
                    var result = MessageBox.Show($"确定要删除配置 '{_currentConfig.Name}' 吗？",
                        "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        await _workflowConfigService.DeleteConfigAsync(_currentConfig.Id);
                        await LoadConfigsAsync();
                        MessageBox.Show("配置删除成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除配置时发生错误");
                MessageBox.Show($"删除配置时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 导出配置
        /// </summary>
        private async void ExportConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentConfig?.Id > 0)
                {
                    var saveDialog = new SaveFileDialog
                    {
                        Filter = "JSON文件|*.json",
                        FileName = $"{_currentConfig.Name}_写书流程配置.json"
                    };

                    if (saveDialog.ShowDialog() == true)
                    {
                        await _workflowConfigService.ExportConfigAsync(_currentConfig.Id, saveDialog.FileName);
                        MessageBox.Show("配置导出成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出配置时发生错误");
                MessageBox.Show($"导出配置时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 导入配置
        /// </summary>
        private async void ImportConfig_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var openDialog = new OpenFileDialog
                {
                    Filter = "JSON文件|*.json"
                };

                if (openDialog.ShowDialog() == true)
                {
                    var config = await _workflowConfigService.ImportConfigAsync(openDialog.FileName);
                    if (config != null)
                    {
                        await LoadConfigsAsync();
                        ConfigListBox.SelectedItem = config;
                        MessageBox.Show("配置导入成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导入配置时发生错误");
                MessageBox.Show($"导入配置时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
